package com.hrd.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hrd.common.util.bean.ServiceResult;
import com.hrd.common.util.date.DateUtils;
import com.hrd.common.util.date.EnumDateStyle;
import com.hrd.mybatis.bean.auto.SqbInvInfo;
import com.hrd.mybatis.bean.auto.SqbInvInfoExample;
import com.hrd.mybatis.bean.auto.SqbWarehouse;
import com.hrd.mybatis.bean.auto.SqbWarehouseExample;
import com.hrd.mybatis.bean.ext.ExtWarehouse;
import com.hrd.mybatis.bean.ext.InvModel;
import com.hrd.service.CommonService;
import com.hrd.service.StatisticsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: wangpeng
 * @Date: 2021/11/1 13:55
 * @Description:
 */
@Slf4j
@Service
public class StatisticsServiceImpl extends BaseServiceImpl implements StatisticsService {
    @Autowired
    private CommonService commonService;

    @Override
    public ServiceResult<List<HashMap<String, String>>> statisticsInv(ExtWarehouse form,boolean isdb) {
        ServiceResult<List<HashMap<String, String>>> result = new ServiceResult<>();
        List<InvModel> ivnList = new ArrayList<>();
        if (StringUtils.isNotBlank(form.getIsClick())) {
            ivnList = getInvList(form,isdb);
        }else{
            ivnList = this.extWarehouseMapper.selectList();
        }
        result.setSuccess(true);
        result.setResult(calculateData(ivnList));
        return result;
    }

    /**
     *  //循环获取库存信息
     * @return
     */
    public List<InvModel> getInvList(ExtWarehouse form,boolean isdb){
        String nowDate = DateUtils.DateToString(new Date(), EnumDateStyle.YYYY_MM_DD);
        String date = StringUtils.isNotBlank(form.getStartTime())?form.getStartTime():nowDate;
        //获取token
        String token = commonService.getAccessToken() == null ? "" : commonService.getAccessToken().getResult();

        List<InvModel> ivnList = new ArrayList<>();


        ServiceResult<List<InvModel>> ivnListResult = commonService.getIvnList(date, token);
        if (ivnListResult != null) {
            List<InvModel> list = ivnListResult.getResult();
            if (CollectionUtils.isNotEmpty(list)) {
                ivnList.addAll(list);
            }
        }

        if (isdb && CollectionUtils.isNotEmpty(ivnList)){
            this.sqbInvInfoMapper.deleteByExample(new SqbInvInfoExample());
            for (InvModel invModel : ivnList) {
                SqbInvInfo sqbInvInfo = new SqbInvInfo();
                sqbInvInfo.setStockidName(invModel.getStockid_name());
                sqbInvInfo.setSpidId(sqbInvInfo.getSpidId());
                sqbInvInfo.setMaterialidName(invModel.getMaterialid_name());
                sqbInvInfo.setMaterialidNumber(invModel.getMaterialid_number());
                sqbInvInfo.setQty(invModel.getQty());
                sqbInvInfo.setStockidId(invModel.getStockid_id());
                this.sqbInvInfoMapper.insert(sqbInvInfo);
            }
        }
        return ivnList;
    }

    /**
     * 计算统计数据
     *
     * @param list
     */
    public List<HashMap<String, String>> calculateData(List<InvModel> list) {
       /* String str = JsonUtil.readJsonFile(new File("F://a.json"));
        list = JSONArray.parseArray(str,InvModel.class);*/
        //按照商品编码分组
        Map<String, List<InvModel>> map = list.stream().collect(Collectors.groupingBy(InvModel::getMaterialid_numberAndName));
        List<HashMap<String, String>> resultList = new ArrayList<>();
        double rowSum = 0;
        HashMap<String, String> rowSumMap = new HashMap<>();
        for (String s : map.keySet()) {
            HashMap<String, List<HashMap>> dataMap = new HashMap<>();
            List<InvModel> invModels = map.get(s);
            //按照仓库id分组
            Map<String, List<InvModel>> collect = invModels.stream().collect(Collectors.groupingBy(InvModel::getStockid_id));

            //每个商品所有仓库库存
            double columnSum = 0;

            HashMap<String, String> stockidSum = new HashMap<>();
            for (String s1 : collect.keySet()) {
                //按仓库库存求和
                double sum = collect.get(s1).stream().mapToDouble(InvModel::doubleQty).sum();
                stockidSum.put(s1, String.valueOf(sum));
                columnSum = columnSum+sum;
                rowSum = rowSum+sum;
                if (StringUtils.isNotBlank(rowSumMap.get(s))){
                    rowSumMap.put(s1,String.valueOf(Double.parseDouble(rowSumMap.get(s))+sum));
                }else{
                    rowSumMap.put(s1,String.valueOf(sum));
                }
            }
            String materialid_name = s.split("<--->")[1];
            stockidSum.put("materialid_name", materialid_name);
            stockidSum.put("sum",String.valueOf(columnSum));
            resultList.add(stockidSum);

        }

        rowSumMap.put("materialid_name","总计");
        rowSumMap.put("sum",String.valueOf(rowSum));
        resultList.add(rowSumMap);
        return resultList;
    }

    @Override
    public List<JSONObject> getcolumns(ExtWarehouse form,boolean isdb) {
        List<JSONObject> list = new ArrayList<>();
        if (StringUtils.isNotBlank(form.getIsClick())) {
            List<InvModel> ivnList = getInvList(form,isdb);
            if (CollectionUtils.isNotEmpty(ivnList)){
                /**
                 * 按仓库分组
                 */
                if (isdb) {
                    this.sqbWarehouseMapper.deleteByExample(new SqbWarehouseExample());
                }
                Map<String, List<InvModel>> map = ivnList.stream().collect(Collectors.groupingBy(InvModel::getStockid_idAndName));
                for (String s : map.keySet()) {
                    String id = s.split("<--->")[0];
                    String name = s.split("<--->")[1];
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("id",id);
                    jsonObject.put("name",name);
                    list.add(jsonObject);
                    if (isdb) {
                        SqbWarehouse sqbWarehouse = new SqbWarehouse();
                        sqbWarehouse.setStockidId(id);
                        sqbWarehouse.setStockidName(name);
                        this.sqbWarehouseMapper.insert(sqbWarehouse);
                    }
                }
            }
        } else {
            List<SqbWarehouse> sqbWarehouses = this.sqbWarehouseMapper.selectByExample(new SqbWarehouseExample());
            for (SqbWarehouse sqbWarehouse : sqbWarehouses) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id",sqbWarehouse.getStockidId());
                jsonObject.put("name",sqbWarehouse.getStockidName());
                list.add(jsonObject);
            }
        }
        return list;
    }
}
